package com.xln.furns.web;

import com.xln.furns.entity.Furn;
import com.xln.furns.entity.Page;
import com.xln.furns.service.FurnService;
import com.xln.furns.service.impl.FurnServiceimpl;
import com.xln.furns.utils.DateUtils;
import com.xln.furns.utils.GetDateTime;
import com.xln.furns.utils.WebUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@WebServlet(name = "FurnServlet", value = "/FurnServlet")
public class FurnServlet extends BasicServlet {
    FurnService furnService = new FurnServiceimpl();

    /**
     * 查询所有家居，不分页
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void furnlist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        System.out.printf("furnlist方法被调用");
        List<Furn> furns = furnService.queryFurn();

            request.setAttribute("furn",furns);

        request.getRequestDispatcher("/views/manage/furn_manage.jsp").forward(request,response);

    }

    /**
     * 添加家居单个
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void addFurn(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        System.out.printf("furnlist方法被调用");
//        String name = request.getParameter("name");
//        String maker = request.getParameter("maker");
//        String price = request.getParameter("price");
//        String sales = request.getParameter("sales");
//        String stock = request.getParameter("stock");
//        String imgpath = "assets/images/product-image/default.jpg";

        //正则方法
//        if (!price.matches("\\d+\\.\\d+")){
//            request.setAttribute("mes","输入价钱数据类型错误！");
//            request.setAttribute("price",price);
//            request.getRequestDispatcher("/views/manage/furn_add.jsp").forward(request,response);
//            return;
//        } else if (!sales.matches("\\d+")){
//            request.setAttribute("mes","输入销量数据类型错误！");
//            request.setAttribute("sales",sales);
//            request.getRequestDispatcher("/views/manage/furn_add.jsp").forward(request,response);
//
//            return;
//        }else if (!stock.matches("\\d+")){
//            request.setAttribute("mes","输入库存数据类型错误！");
//            request.setAttribute("stock",stock);
//            request.getRequestDispatcher("/views/manage/furn_add.jsp").forward(request,response);
//
//            return;
//        }
//        Furn furn = new Furn(null,name,maker,new BigDecimal(price),new Integer(sales),new Integer(stock),imgpath);
//        furnService.addFurn(furn);
//        response.sendRedirect(request.getContextPath()+"/FurnServlet?action=furnlist");


        //类型强制转换法
//        try{
//            int price1 = Integer.parseInt(price);
//            Furn furn = new Furn(null,name,maker,new BigDecimal(price),new Integer(sales),new Integer(stock),imgpath);
//            furnService.addFurn(furn);
//            response.sendRedirect(request.getContextPath()+"/FurnServlet?action=furnlist");
//        }catch (NumberFormatException e){
//            request.setAttribute("mes","输入库存数据类型错误！");
//            request.getRequestDispatcher("/views/manage/furn_add.jsp").forward(request,response);
//              return;
//        }

        //异常法
//        try {
//            Furn furn = new Furn(null,name,maker,new BigDecimal(price),new Integer(sales),new Integer(stock),imgpath);
//            furnService.addFurn(furn);
//            response.sendRedirect(request.getContextPath()+"/FurnServlet?action=furnlist");
//        }catch (NumberFormatException e){
//            request.setAttribute("mes","输入数据类型错误！");
//            request.getRequestDispatcher("/views/manage/furn_add.jsp").forward(request,response);
//            return;
//        }

        //BeanUtils工具法
//        try {
//            BeanUtils.populate(furn,request.getParameterMap());
//        } catch (IllegalAccessException e) {
//            throw new RuntimeException(e);
//        } catch (InvocationTargetException e) {
//            throw new RuntimeException(e);
//        }
        //封装放入工具包中
        Furn furn = DateUtils.copyParamToBean(request.getParameterMap(),new Furn());
        furnService.addFurn(furn);
        response.sendRedirect(request.getContextPath()+"/FurnServlet?action=page&pageNo="+request.getParameter("pageNo"));

    }
    protected void deleteFurn(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{

        int id = DateUtils.parseInt(request.getParameter("id"),0);
        furnService.deleteFurn(id);

        request.getRequestDispatcher("/FurnServlet?action=page&pageNo="+request.getParameter("pageNo")).forward(request,response);

    }


    /**
     * 通过id查询家居
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void queryFurnById(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{

        Integer id = DateUtils.parseInt(request.getParameter("id"),0);
        Furn furn = furnService.queryFurnById(id);
        request.setAttribute("furn",furn);
        request.getRequestDispatcher("/views/manage/furn_update.jsp").forward(request,response);

    }

    /**
     * 更新家居
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void updateFurn(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
        Furn furn = DateUtils.copyParamToBean(request.getParameterMap(),new  Furn());
        furnService.updateFurn(furn);
        response.sendRedirect( request.getContextPath()+"/FurnServlet?action=page&pageNo="+request.getParameter("pageNo"));
    }

    /**
     * 更新家居，包括图片上传
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void updateFurnUpload(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
        //     Furn furn = DateUtils.copyParamToBean(request.getParameterMap(),new  Furn());
    //     furnService.updateFurn(furn);
    //     response.sendRedirect( request.getContextPath()+"/FurnServlet?action=page&pageNo="+request.getParameter("pageNo"));
    //
        Integer id = DateUtils.parseInt(request.getParameter("id"),0) ;
        Furn furn = furnService.queryFurnById(id);

        /**
         * 渗透测试改进使用
         */
        // if (furn == null){
        //     // request.setAttribute("error","错误，未找到商品！");
        // }else { }

        //判断是不是文件表单(enctype="multipart/form-data")
        if (ServletFileUpload.isMultipartContent(request)){
        //创建DiskFileItemFactory对象，用于构建—个解析上传数据的工具对象
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            // 创建一个解折上传数据的工具对象
            ServletFileUpload servletFileUpload =
                    new ServletFileUpload(diskFileItemFactory);
            servletFileUpload.setHeaderEncoding("utf-8");

        //    关键的地方，servletFileUpload对象可以把表单提交的数据text /文件
            //  将其封装到 FileItem文件项中
            try {
                List<FileItem> list = servletFileUpload.parseRequest(request);
                for (FileItem fileItem : list) {
                    //    ”判断是不是一个文件
                    if (fileItem.isFormField()) {//如果是true就是文本 input text
                        if ("name".equals(fileItem.getFieldName())) {
                            furn.setName(fileItem.getString("utf-8"));
                        } else if ("maker".equals(fileItem.getFieldName())) {
                            furn.setMaker(fileItem.getString("uft-8"));
                        } else if ("price".equals(fileItem.getFieldName())) {
                            furn.setPrice(new BigDecimal(fileItem.getString()));
                        } else if ("sales".equals(fileItem.getFieldName())) {
                            furn.setSales(new Integer(fileItem.getString()));
                        } else if ("stock".equals(fileItem.getFieldName())) {
                            furn.setStock(new Integer(fileItem.getString()));
                        }

                    }else {

                        String name = fileItem.getName();
                        System.out.printf("name="+name);
                        if (!name.equals("")) {
                            String filePath = "/" + WebUtils.FURN_IMG_DIRECTORY;
                            String realPath = request.getServletContext().getRealPath(filePath+ "/"+ GetDateTime.getDateTime());
                            File fileRealPathDirectory = new File(realPath);
                            if (!fileRealPathDirectory.exists()) {
                                fileRealPathDirectory.mkdirs(); //不存在就创建目录

                            }
                            name = UUID.randomUUID().toString() + "_" + System.currentTimeMillis() + "_" + name;
                            String fileFullPath = fileRealPathDirectory + "/" + name;
                            fileItem.write(new File(fileFullPath));
                            fileItem.getOutputStream().close(); // 关闭流

                            furn.setImgpath(WebUtils.FURN_IMG_DIRECTORY + "/" + GetDateTime.getDateTime() + "/" + name);
                        }

                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        furnService.updateFurn(furn);

        request.getRequestDispatcher("/views/manage/furn_update_ok.jsp").forward(request,response);
    }
    /**
     * 首页分页
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void page(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
        int pageNo = DateUtils.parseInt(request.getParameter("pageNo"),1);
        int pageSize = DateUtils.parseInt(request.getParameter("pageSize"), Page.PAGE_SIZE);
        Page<Furn> page = furnService.page(pageNo,pageSize);
        request.setAttribute("page",page);
        request.getRequestDispatcher("/views/manage/furn_manage.jsp").forward(request,response);
//        System.out.printf("page:"+page);


    }
}

